import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:ui';
import 'package:dio/dio.dart';
// 页面
import './msg_user.dart';
import './all_user.dart';
import './user_statisti.dart';
class HomePages extends StatefulWidget {
  _HomePagesState createState() => _HomePagesState();
}

class tabItem {
  final String title;
  final int icon;
  final int num;
  final Widget cont;
  tabItem({@required this.title,@required this.cont,@required this.icon,this.num = 0});
}

class _HomePagesState extends State<HomePages> with SingleTickerProviderStateMixin {
  TabController mController;
  List<tabItem> tabList = [];
  Map csuser;
  int _tabIndex;
  @override
  void initState() {
    super.initState();
    _tabIndex = 0;
    tabList
      ..add(tabItem(
        title: '消息',
        num: 1,
        icon: 0xe61c,
        cont: MsgUserList(),
      ))
      ..add(tabItem(
        title: '联系人',
        // num: 0,
        icon: 0xe624,
        cont: AllUserList(),
      ))
      ..add(tabItem(
        title: '统计',
        // num: 0,
        icon: 0xe642,
        cont: UserStatisti(),
      ));
    csuser = {
      'wxname': '',
      'username': '***********',
      'nickname':'******',
      'id': 0
    };
    getCuUser();
    mController = TabController(
      initialIndex: _tabIndex,
      length: tabList.length,
      vsync: this,
    );
    mController.addListener(() {
      setTabIndex(mController.index);
    });
  }
  @override

  void getCuUser () {
    Dio().get(
      'https://hinode.shangning.site/api/csuser/getcsuser',
      data: {
        'id' : 1138
      }
    ).then((response){
      setState(() {
        csuser = response.data['cs_info'];
        if (csuser['header_url'] == '') {
          csuser['header_url'] = null;
        } else {
          csuser['header_url'] = 'https://hi.shangning.org.cn/' + csuser['header_url'];
        }
      });
    });
  }

  void setTabIndex (int index) {
    setState(() {
      _tabIndex = index;
    });
  }
  List<Widget> rendetTabBar () {
    List<Widget> tabItemList = [];
    for (int i = 0; i < tabList.length; i++) {
      Color activeColor = i == _tabIndex ? Color.fromRGBO(14, 139, 255, 1) : Color.fromRGBO(141, 144, 151, 1);
      double itemWidth = 750 / tabList.length;
      double badgeLeft = itemWidth/2 + 10;
      tabItemList..add(
        GestureDetector(
          child: Stack(
            children: <Widget>[
              Container(
                width: ScreenUtil().setWidth(itemWidth.toInt()),
                height: ScreenUtil().setWidth(96),
                padding: EdgeInsets.all(ScreenUtil().setWidth(6)),
                color: Colors.white,
                child: Column(
                  children: <Widget>[
                    Icon(
                      IconData(tabList[i].icon, fontFamily: 'iconfont'),
                      color: activeColor,
                      size: ScreenUtil().setWidth(50),
                    ),
                    Text(
                      tabList[i].title,
                      style: TextStyle(
                        color: activeColor,
                        fontSize: ScreenUtil().setWidth(22)
                      ),
                    )
                  ],
                ),
              ),
              Positioned(
                top: ScreenUtil().setWidth(5),
                left:ScreenUtil().setWidth(badgeLeft.toInt()),
                child: Badge(
                  num: tabList[i].num,
                ),
              )
            ],
          ),
          onTap: () {
            setState(() {
              mController.index = i;
            });
          },
        )
      );
    }
    return tabItemList;
  }

  Widget build(BuildContext context) {
    return Container(
      child: Scaffold(
        drawer: new Drawer(
          semanticLabel: '客服详情',
          child: Column(
            children: <Widget>[
              Stack(
                children: <Widget>[
                  Container(
                    height: ScreenUtil().setWidth(340),
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: csuser['header_url'] == null ? AssetImage('static/defaultimg.jpg'):NetworkImage(csuser['header_url']),
                        fit: BoxFit.cover,
                      )
                    ),
                  ),
                  BackdropFilter(
                    filter: ImageFilter.blur(sigmaX: 20.0,sigmaY: 10.0),
                    child: Opacity(
                      opacity: 0.5,
                      child: Container(
                        height: ScreenUtil().setWidth(340),
                        decoration: BoxDecoration(
                          color:Color.fromRGBO(0, 0, 0, 0.3)
                        ),
                      ),
                    )
                  ),
                  Container(
                    padding: EdgeInsets.fromLTRB(
                      ScreenUtil().setWidth(29), 
                      ScreenUtil().setWidth(74), 
                      ScreenUtil().setWidth(29), 
                      ScreenUtil().setWidth(34)
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Container(
                              width: ScreenUtil().setWidth(130),
                              height: ScreenUtil().setWidth(130),
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                  // image: NetworkImage(
                                  //   csuser['header_url'] == null ? 'static/defaultimg.jpg' : csuser['header_url']
                                  // ),
                                  image: csuser['header_url'] == null ? AssetImage('static/defaultimg.jpg'):NetworkImage(csuser['header_url']),
                                  fit: BoxFit.cover
                                ),
                                borderRadius: BorderRadius.circular(50)
                              ),
                            )
                          ],
                        ),
                        Container(
                          margin: EdgeInsets.fromLTRB(
                            ScreenUtil().setWidth(0),
                            ScreenUtil().setWidth(30),
                            ScreenUtil().setWidth(0),
                            ScreenUtil().setWidth(0)
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                csuser['nickname'],
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: ScreenUtil().setWidth(28),
                                  fontWeight: FontWeight.w600
                                ),
                              ),
                              SizedBox(
                                height: ScreenUtil().setWidth(10),
                              ),
                              Text(
                                csuser['username'],
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: ScreenUtil().setWidth(22),
                                ),
                              )
                            ]
                          )
                        )
                      ],
                    ),
                  )
                ],
              ),
              Expanded(
                child: ListView(
                  padding: EdgeInsets.all(0),
                  children: <Widget>[
                    ListTile(
                      leading: Icon(Icons.cloud_off),
                      title: Text('离线回复'),
                      onTap: (){
                        Navigator.pop(context);
                      },
                    ),
                    Divider(
                      height: 0,
                      color: Colors.grey[400],
                    ),
                    ListTile(
                      leading: Icon(Icons.timer),
                      title: Text('超时回复'),
                      onTap: (){},
                    ),
                    Divider(
                      height: 0,
                      color: Colors.grey[400],
                    ),
                    ListTile(
                      leading: Icon(Icons.send),
                      title: Text('消息群发'),
                      onTap: (){},
                    ),
                    Divider(
                      height: 0,
                      color: Colors.grey[400],
                    ),
                    ListTile(
                      leading: Icon(Icons.settings),
                      title: Text('设置'),
                      onTap: (){},
                    ),
                    Divider(
                      height: 0,
                      color: Colors.grey[400],
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
        body: Builder(
          builder: (context) {
            return Column(
              children: <Widget>[
                Expanded(
                  child: TabBarView(
                    controller: mController,
                    children: tabList.map((item) {
                      return item.cont;
                    }).toList(),
                  ),
                ),
                Container(
                  width:  ScreenUtil().setWidth(750),
                  height:  ScreenUtil().setWidth(100),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border(
                      top: BorderSide(
                        width: 1,
                        color: Color.fromRGBO(243, 243, 243, 1)
                      )
                    )
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: rendetTabBar(),
                  ),
                )
              ],
            );
          },
        ),
      ),
    );
  }
}

class Badge extends StatelessWidget {
  int num;
  Badge({Key key, @required this.num}):super(key:key);
  @override
  Widget build(BuildContext context) {
    var width;
    var text = '$num';
    if(this.num < 10 && this.num > 0){
      width = ScreenUtil().setWidth(26);
    } else if (this.num > 10 && this.num < 100) {
      width = ScreenUtil().setWidth(40);
    } else if (this.num >= 100) {
      width = ScreenUtil().setWidth(50);
      text = '99+';
    } else {
      return Container();
    }
    return Container(
      width: width,
      height: ScreenUtil().setWidth(26),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Color.fromRGBO(255, 93, 87, 1),
        borderRadius: BorderRadius.circular(16.0)
      ),
      child: Text(
        text,
        style: TextStyle(
          fontSize: ScreenUtil().setWidth(16),
          color: Colors.white
        ),
      ),
    );
  }
}